/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.id;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.ibatis.reflection.MetaObject;

import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.entity.JEntityColumn;
import com.jianggujin.dbfly.mybatis.entity.JEntityIdColumn;
import com.jianggujin.dbfly.mybatis.entity.JEntityResolver;
import com.jianggujin.dbfly.mybatis.util.JMetaObjectUtils;
import com.jianggujin.dbfly.util.JDBFlyException;

/**
 * 主键生成工具
 * 
 * @author jianggujin
 *
 */
public class JIdGeneratorUtils {

    /**
     * 缓存
     */
    private static final Map<Class<? extends JIdGenerator>, JIdGenerator> CACHE = new ConcurrentHashMap<Class<? extends JIdGenerator>, JIdGenerator>();

    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 生成 Id
     *
     * @param target
     * @param entityClass
     * @param property
     * @throws JDBFlyException
     */
    public static void generateId(Object target, Class<?> entityClass, String property) throws JDBFlyException {
        JEntity entity = JEntityResolver.getEntity(entityClass);
        JEntityColumn column = entity.getColumn(property);
        if (column == null || !(column instanceof JEntityIdColumn)) {
            return;
        }
        JEntityIdColumn idColumn = (JEntityIdColumn) column;
        Class<? extends JIdGenerator> idGeneratorClass = idColumn.getIdGeneratorClass();
        try {
            JIdGenerator idGenerator;
            if (CACHE.containsKey(idGeneratorClass)) {
                idGenerator = CACHE.get(idGeneratorClass);
            } else {
                LOCK.lock();
                try {
                    if (!CACHE.containsKey(idGeneratorClass)) {
                        CACHE.put(idGeneratorClass, idGeneratorClass.newInstance());
                    }
                    idGenerator = CACHE.get(idGeneratorClass);
                } finally {
                    LOCK.unlock();
                }
            }
            MetaObject metaObject = JMetaObjectUtils.forObject(target);
            if (metaObject.getValue(property) == null) {
                metaObject.setValue(property, idGenerator.generateId(entity, idColumn));
            }
        } catch (Exception e) {
            throw new JDBFlyException("生成ID失败", e);
        }
    }

    /**
     * 生成多个Id
     *
     * @param target
     * @param entityClass
     * @param propertiesJoin
     * @throws JDBFlyException
     */
    public static void generateIds(Object target, Class<?> entityClass, String propertiesJoin) throws JDBFlyException {
        JEntity entity = JEntityResolver.getEntity(entityClass);
        String[] properties = propertiesJoin.split(",");
        try {
            for (String property : properties) {
                JEntityColumn column = entity.getColumn(property);
                if (column == null || !(column instanceof JEntityIdColumn)) {
                    return;
                }
                JEntityIdColumn idColumn = (JEntityIdColumn) column;
                Class<? extends JIdGenerator> idGeneratorClass = idColumn.getIdGeneratorClass();
                JIdGenerator idGenerator;
                if (CACHE.containsKey(idGeneratorClass)) {
                    idGenerator = CACHE.get(idGeneratorClass);
                } else {
                    LOCK.lock();
                    try {
                        if (!CACHE.containsKey(idGeneratorClass)) {
                            CACHE.put(idGeneratorClass, idGeneratorClass.newInstance());
                        }
                        idGenerator = CACHE.get(idGeneratorClass);
                    } finally {
                        LOCK.unlock();
                    }
                }
                MetaObject metaObject = JMetaObjectUtils.forObject(target);
                if (metaObject.getValue(property) == null) {
                    metaObject.setValue(property, idGenerator.generateId(entity, idColumn));
                }
            }
        } catch (Exception e) {
            throw new JDBFlyException("生成ID失败", e);
        }
    }

}
